package com.sx.core.mybatis;

import com.sx.core.page.Pageable;
import com.sx.core.page.Sort;
import org.apache.ibatis.session.RowBounds;

import java.io.Serializable;

/**
 * Created by lihao on 2017/3/27.
 */
public class Pagination extends RowBounds implements Pageable,Serializable {

    private final int page;
    private final int size;
    private Sort sort;

    public Pagination(int page, int size) {
        this(page, size, null);
    }
    public Pagination(int page, int size, Sort.Direction direction, String... properties) {
        this(page, size, new Sort(direction, properties));
    }

    public Pagination(int page, int size, Sort sort) {
        super((page-1)*size,size);
        this.sort = sort;
        this.page = page;
        this.size = size;
    }

    @Override
    public Pageable first() {
        return new Pagination(0, getPageSize(), getSort());
    }

    @Override
    public int getPageNumber() {
        return page;
    }

    @Override
    public int getPageSize() {
        return size;
    }

    @Override
    public Sort getSort() {
        return sort;
    }

    @Override
    public boolean hasPrevious() {
        return page > 0;
    }

    @Override
    public Pageable next() {
        return new Pagination(getPageNumber() + 1, getPageSize(), getSort());
    }

    public Pageable previous() {
        return getPageNumber() == 0 ? this : new Pagination(getPageNumber() - 1, getPageSize(), getSort());
    }

    @Override
    public Pageable previousOrFirst() {
        return hasPrevious() ? previous() : first();
    }
    @Override
    public int hashCode() {

        final int prime = 31;
        int result = 1;

        result = prime * result + page;
        result = prime * result + size;

        return result;
    }
    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        Pagination other = (Pagination) obj;
        return this.page == other.page && this.size == other.size;
    }
}
